package com.swcw.platform.utils.bean;

import java.security.MessageDigest;
import java.util.Arrays;

import com.swcw.platform.utils.WechatHead;


/**
 * 鉴权模块
 *
 * @author  杨坚
 * @version  [版本号, 2016-3-19]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public abstract class WechatAuth
{
    /**
     * 身份识别，识别请求是否来自微信平台
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static boolean identify(WechatHead head, String userToken)
    {
        String signature = head.getSignature();
        String timestamp = head.getTimestamp();
        String nonce = head.getNonce();
        String[] tmpArr = {userToken, timestamp, nonce};
        Arrays.sort(tmpArr);
        String tmpStr = ArrayToString(tmpArr);
        tmpStr = SHA1Encode(tmpStr);

        //带过来的签名和本地计算的一致则身份校验成功
        if (signature.equalsIgnoreCase(tmpStr))
        {
            return true;
        }

        return false;
    }

    /**
     * 数组转字符串
     * @param arr
     * @return
     * @see [类、类#方法、类#成员]
     */
    private static String ArrayToString(String[] arr)
    {
        StringBuffer bf = new StringBuffer();
        for (int i = 0; i < arr.length; i++)
        {
            bf.append(arr[i]);
        }
        return bf.toString();
    }

    /**
     * sha1加密
     * @param sourceString
     * @return
     * @see [类、类#方法、类#成员]
     */
    private static String SHA1Encode(String sourceString)
    {
        String resultString = null;
        try
        {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            resultString = byte2hexString(md.digest(sourceString.getBytes()));
        }
        catch (Exception ex)
        {
            //TODO log
        }
        return resultString;
    }

    /**
     * byte转换成字符串
     * @param bytes
     * @return
     * @see [类、类#方法、类#成员]
     */
    private static final String byte2hexString(byte[] bytes)
    {
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++)
        {
            if (((int)bytes[i] & 0xff) < 0x10)
            {
                buf.append("0");
            }
            buf.append(Long.toString((int)bytes[i] & 0xff, 16));
        }
        return buf.toString().toUpperCase();
    }
}
